package com.hk.demo.player.grid;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import com.hk.demo.player.R;
import com.hk.player.core.MonitorMediaData;
import com.zhoug.common.adapters.recycler.dividers.GridItemDecoration;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * ViewPager适配器,每个页面都是一个RecyclerView
 *
 * @author: zhoug
 * @since: 2025-08-15
 */
public class VideoPagerAdapter extends RecyclerView.Adapter<VideoPagerAdapter.PageViewHolder> {
    private static final String TAG = ">>>VideoPagerAdapter";
    private final Context mContext;
    private final List<MonitorMediaData> mData = new ArrayList<>();
    private int mGridMode;//布局模式
    private int mPreviousMode;//上一次的布局模式
    private Lifecycle mLifecycle;
    private int mLastPosition = -1;
    private int mCurrentPosition = -1;
    private int mPagerHeight = 0;//页面高度
    private RecyclerView mPagerRecyclerView;


    public VideoPagerAdapter(@NonNull Context context, int gridMode, Lifecycle lifecycle) {
        this.mContext = context;
        this.mGridMode = gridMode;
        this.mPreviousMode = gridMode;
        this.mLifecycle = lifecycle;
        if (mLifecycle != null) {
            mLifecycle.addObserver(new DefaultLifecycleObserver() {
                @Override
                public void onDestroy(@NonNull LifecycleOwner owner) {
                    removeViewPagerHeightListener();
                    release();
                }
            });
        }

    }

    public void setData(List<MonitorMediaData> data) {
        this.mData.clear();
        if (data != null && !data.isEmpty()) {
            this.mData.addAll(data);
        }
        notifyDataSetChanged();
    }

    /**
     * 开始播放当前页的所有视频
     *
     * @param position
     */
    public void startPlay(int position) {
        mLastPosition = mCurrentPosition;
        mCurrentPosition = position;
        //停止播放上个页面的视频
        pausePlay(mLastPosition);
        PageViewHolder currentViewHolder = findViewHolder(mCurrentPosition);
        if (currentViewHolder != null) {
            LogUtils.d(TAG, StringUtils.format("开始播放第%d页视频", mCurrentPosition));
            currentViewHolder.startPlay();
        }
    }

    /**
     * 停止播放当前页的所有视频
     *
     * @param position
     */
    public void stopPlay(int position) {
        PageViewHolder lastViewHolder = findViewHolder(position);
        if (lastViewHolder != null) {
            LogUtils.d(TAG, StringUtils.format("停止播放第%d页视频", position));
            lastViewHolder.stopPlay();
        }
    }

    /**
     * 暂停播放当前页的所有视频
     *
     * @param position
     */
    public void pausePlay(int position) {
        PageViewHolder lastViewHolder = findViewHolder(position);
        if (lastViewHolder != null) {
            LogUtils.d(TAG, StringUtils.format("暂停播放第%d页视频", position));
            lastViewHolder.pausePlay();
        }
    }


    public void release() {
        if (mPagerRecyclerView != null) {
            int childCount = mPagerRecyclerView.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = mPagerRecyclerView.getChildAt(i);
                try {
                    RecyclerView.ViewHolder childViewHolder = mPagerRecyclerView.getChildViewHolder(child);
                    if (childViewHolder instanceof PageViewHolder pageViewHolder) {
                        pageViewHolder.releasePlayer();
                    }
                } catch (Exception e) {
                    LogUtils.e(TAG, "release:");
                }
            }
        }

    }

    /**
     * 找到给定的position位置的ViewHolder
     *
     * @param position
     * @return
     */
    private PageViewHolder findViewHolder(int position) {
        if (mPagerRecyclerView != null && position >= 0) {
            return (PageViewHolder) mPagerRecyclerView.findViewHolderForAdapterPosition(position);
        }
        return null;
    }

    /**
     * 设置布局模式
     *
     * @param gridMode
     */
    public void setGridMode(int gridMode) {
        this.mPreviousMode = this.mGridMode;
        this.mGridMode = gridMode;
    }

    /**
     * 获取上一次的布局模式
     *
     * @return
     */
    public int getPreviousMode() {
        return mPreviousMode;
    }

    private int getDataSize() {
        return mData.size();
    }

    @Override
    public int getItemCount() {
        int totalItems = mData.size();
        int itemsPerPage = getItemsPerPage();
        return (int) Math.ceil((double) totalItems / itemsPerPage);
    }


    /**
     * 每页数据条数
     *
     * @return
     */
    private int getItemsPerPage() {
        return GridMode.getItemsPerPage(mGridMode);
    }

    @NonNull
    @Override
    public PageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.grid_player_page, parent, false);
        PageViewHolder pageViewHolder = new PageViewHolder(view);
        LogUtils.d(TAG, "onCreateViewHolder:" + pageViewHolder);
        return pageViewHolder;
    }


    @Override
    public void onBindViewHolder(@NonNull PageViewHolder holder, int position) {
        LogUtils.d(TAG, "onBindViewHolder:" + position + ",holder:" + holder);
        holder.bindPage(position);
    }


    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        LogUtils.d(TAG, "onAttachedToRecyclerView:");
        mPagerRecyclerView = recyclerView;
        addViewPagerHeightListener();
    }

    @Override
    public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        LogUtils.d(TAG, "onDetachedFromRecyclerView:");
        removeViewPagerHeightListener();
        mPagerRecyclerView = null;
    }

    @Override
    public void onViewDetachedFromWindow(@NonNull PageViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
        LogUtils.d(TAG, "onViewDetachedFromWindow:" + holder.mPosition);
        holder.releasePlayer();
    }

    /**
     * 监听ViewPager页面的高度变化
     */
    private void addViewPagerHeightListener() {
        if (mPagerRecyclerView == null) return;
        // 添加布局监听器以获取父容器高度
        mPagerRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);

    }

    /**
     * 移除ViewPager页面的高度监听
     */
    private void removeViewPagerHeightListener() {
        if (mPagerRecyclerView != null) {
            mPagerRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
        }
    }

    //notifyDataSetChanged会导致重建Item,视频状态不能保持
    private final ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            // 获取父容器高度并设置到适配器
            if (mPagerRecyclerView != null) {
                int parentHeight = mPagerRecyclerView.getHeight();
                if (parentHeight > 0 && mPagerHeight != parentHeight) {
                    mPagerHeight = parentHeight;
                    LogUtils.d(TAG, "mPagerHeight:" + mPagerHeight);
                    //找到每一页的PageViewHolder通知高度改变
                    RecyclerViewUtils.findViewHolder(mPagerRecyclerView, (Consumer<PageViewHolder>) viewHolder -> {
                        if (viewHolder != null) {
                            viewHolder.notifyParentHeightChange();
                        }
                    });
                }
            }

        }
    };

    /**
     * 每页ViewHolder
     */
    class PageViewHolder extends RecyclerView.ViewHolder {
        private VideoGridAdapter mGridAdapter;
        private final int mSpacing;
        private final RecyclerView mGridRecyclerView;
        private GridLayoutManager mLayoutManager;
        private int mPosition;

        PageViewHolder(@NonNull View itemView) {
            super(itemView);
            mGridRecyclerView = (RecyclerView) itemView;
            mSpacing = (int) (mContext.getResources().getDimension(R.dimen.dp1) * 2);
            setupGridLayout();
        }

        /**
         * 设置网格布局
         */
        private void setupGridLayout() {
            int spanCount = (int) Math.sqrt(mGridMode);
            mLayoutManager = new GridLayoutManager(mContext, spanCount);
            mGridRecyclerView.setLayoutManager(mLayoutManager);
            // 设置网格适配器
            mGridAdapter = new VideoGridAdapter(mContext, spanCount, mSpacing);
            mGridAdapter.setParentHeight(mPagerHeight);
            //添加分各项
            GridItemDecoration gridItemDecoration = new GridItemDecoration.Builder(mContext)
                    .setColor(Color.parseColor("#ffffff"))
                    .setHorizontalSpan(mSpacing)
                    .setVerticalSpan(mSpacing)
                    .setDrawBound(false, false, false, false)
                    .build();
            mGridRecyclerView.addItemDecoration(gridItemDecoration);
            mGridRecyclerView.setAdapter(mGridAdapter);

        }


        void bindPage(int pagePosition) {
            this.mPosition = pagePosition;
            int itemsPerPage = getItemsPerPage();
            int start = pagePosition * itemsPerPage;
            int end = Math.min(start + itemsPerPage, getDataSize());

            List<MonitorMediaData> pageVideos = mData.subList(start, end);
            if (mGridAdapter != null) {
                mGridAdapter.setParentPosition(pagePosition);
                mGridAdapter.setParentHeight(mPagerHeight);
                mGridAdapter.setData(pageVideos);
                mGridAdapter.notifyDataSetChanged();
            }
        }

        /**
         * 高度变化时调用
         */
        public void notifyParentHeightChange() {
            ////找到网格videoViewHolder通知高度改变
            findViewHolder(videoViewHolder -> {
                mGridAdapter.setParentHeight(mPagerHeight);
                videoViewHolder.notifyItemHeightChange();
            });
        }

        /**
         * 开始播放
         */
        void startPlay() {
            findViewHolder(VideoGridAdapter.VideoViewHolder::startPlay);
        }

        /**
         * 停止播放
         */
        void stopPlay() {
            findViewHolder(VideoGridAdapter.VideoViewHolder::stopPlay);

        }

        /**
         * 暂停播放
         */
        void pausePlay() {
            findViewHolder(VideoGridAdapter.VideoViewHolder::pausePlay);
        }

        /**
         * 是否资源
         */
        void releasePlayer() {
            findViewHolder(VideoGridAdapter.VideoViewHolder::releasePlayer);
        }

        void findViewHolder(@NonNull Consumer<VideoGridAdapter.VideoViewHolder> consumer) {
            if (mGridRecyclerView != null) {
                RecyclerViewUtils.findViewHolder(mGridRecyclerView, consumer);
            }
        }

    }


}
